package com.yu.xcx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.xcx.dto.FollowCount;
import com.yu.xcx.dto.Result;
import com.yu.xcx.entity.Follow;
import com.yu.xcx.entity.ShopFollow;
import com.yu.xcx.mapper.FollowMapper;
import com.yu.xcx.mapper.ShopFollowMapper;
import com.yu.xcx.service.IFollowService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private ShopFollowMapper shopFollowMapper;

    @Override
    public Result follow(Integer userId ,Integer followUserId, Boolean isFollow) {

        if (!isFollow){
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean flag = save(follow);
            if (flag){
                return Result.ok("添加关注成功");
            }else {
                return Result.fail("添加关注失败");
            }
        }
        else {
            QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId).eq("follow_user_id",followUserId);
            boolean flag = remove(queryWrapper);
            if (flag){
                return Result.ok("取消关注成功");
            }else {
                return Result.fail("取消关注失败");
            }
        }
    }

    @Override
    public Result isFollow(Integer userId, Integer followUserId) {
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Integer count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        // 3.判断
        return Result.ok(count > 0);
    }

    @Override
    public Result getFollowCount(Integer userId) {
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("user_id",userId);
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("follow_user_id", userId);
        FollowCount followCount = new FollowCount();
        //添加关注人数
        followCount.setFollowUserCount(count(queryWrapper1));
        //添加粉丝人数
        followCount.setBeFollowedCount(count(queryWrapper2));
        //添加收藏商品数量
        followCount.setFollowShopCount(shopFollowMapper.getCountByUser(userId));

        return Result.ok(followCount);
    }
}
